package cn.fl.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.upload.api.IAttachmentConfigQueryApiService;
import cmm.comm.facade.upload.dto.req.AttachmentConfigQueryApiReqDTO;
import cmm.comm.facade.upload.dto.req.AttachmentExternalRuleEnginApiReqDTO;
import cmm.comm.facade.upload.dto.resp.AttachmentConfigDataFileRespDTO;
import cmm.comm.facade.upload.dto.resp.AttachmentConfigDataRespDTO;
import cmm.comm.facade.upload.dto.resp.AttachmentDataDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.fileconfig.condition.FileCfgConditonQC;
import cn.fl.fileconfig.dto.FileCfgConditionDTO;
import cn.fl.fileconfig.service.IFileCfgConditionApiService;
import cn.fl.project.vo.PrjFileInfoVO;
import cn.fl.upload.constant.UploadConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.service.ISysUlDatCfgService;
import cn.fl.system.transform.SysUlDatCfgVOTransform;
import cn.fl.system.vo.SysUlDatCfgVO;

/**
 * @Description: 上传资料配置表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class SysUlDatCfgServiceImpl implements ISysUlDatCfgService {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(SysUlDatCfgServiceImpl.class);

    /**
     * TODO 自定义 API 暴露服务
     */
    @Autowired
    private IUploadApiService uploadApiService;

    /*附件配置规则引擎查询条件服务类*/
    @Autowired
    private IFileCfgConditionApiService fileCfgConditionApiService;

    @Autowired
    private IAttachmentConfigQueryApiService attachmentConfigQueryApiService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Override
    public SysUlDatCfgVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) {
            return null;
        }
        //TODO 业务逻辑
        SysUlDatCfgDTO dto = null;//this.自定义ApiService.selectById(id);
        return SysUlDatCfgVOTransform.toVO(dto);
    }

    @Override
    public Long add(SysUlDatCfgVO entity) throws BaseException {
        if (null == entity) {
            BaseLogUtils.info(logger, "add", "新增上传资料配置失败,上传资料配置对象为空.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
        }
        return this.uploadApiService.addSysUlDatCfg(SysUlDatCfgVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) {
            BaseLogUtils.info(logger, "removeByIds", "删除上传资料配置失败,主键参数为空.IDS:" + JSONObject.toJSONString(ids), CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
        }
        return this.uploadApiService.removeSysUlDatCfgByIds(ids);
    }

    @Override
    public boolean modify(SysUlDatCfgVO entity) throws BaseException {
        if (null == entity) return false;
        //return this.sysUlDatCfgApiService.modify(SysUlDatCfgVOTransform.toDTO(entity));
        //TODO 业务逻辑
        return false;
    }

    @Override
    public List<SysUlDatCfgVO> searchList(SysUlDatCfgQueryCondition condition)
            throws BaseException {
        if (null == condition || StringUtils.isBlank(condition.getOrgCd())) {
            BaseLogUtils.info(logger, "searchList", "查询所有上传资料配置失败,组织架构代码为空.DATA:" + JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
        }
        List<SysUlDatCfgDTO> list = this.uploadApiService.searchSysUlDatCfgList(condition);
        return SysUlDatCfgVOTransform.toVOList(list);
    }


    @Override
    public List<PrjFileInfoVO> searchFileCfgList(FileCfgConditonQC fileCfgConditonQC,String isShowSts) {
        List<PrjFileInfoVO> voList=null;
        try {
            List<AttachmentDataDTO> list = this.getAttachmentFile(fileCfgConditonQC);
            //拼装JSON
            BaseLogUtils.info(logger, "searchFileCfgList", "拼接响应JSON数据开始...");
            voList=this.getPrjFileInfoVO(list,isShowSts);
            BaseLogUtils.newLogger("获取资料配置返回结果voList=" + JSON.toJSONString(voList)).info();
            BaseLogUtils.info(logger, "searchFileCfgList", "拼接响应JSON数据成功...");
        } catch (Exception e) {
            BaseLogUtils.error(logger, "searchFileCfgList", "获取资料配置失败" + e.toString(), e);
            throw new BaseException("获取资料配置失败，请联系管理员！");
        }
        return voList;
    }

    @Override
    public  List<AttachmentDataDTO> getAttachmentFile(FileCfgConditonQC fileCfgConditonQC) {
        List<AttachmentDataDTO> list = null;
        try {
            BaseLogUtils.info(logger, "getAttachmentFile", "获取查询条件...");
            /*获取规则引擎的查询条件封装类*/
            FileCfgConditionDTO fileCfgConditionDTO = fileCfgConditionApiService.getFileCfgConditon(fileCfgConditonQC);
            BaseLogUtils.info(logger, "getAttachmentFile", fileCfgConditionDTO.toString());
            /*封装规则引擎服务查询条件*/
            AttachmentConfigQueryApiReqDTO attachmentConfigQueryApiReqDTO = new AttachmentConfigQueryApiReqDTO();
            List<AttachmentExternalRuleEnginApiReqDTO> attList = new ArrayList<>();
            /*获取资料类型数组*/
            List<String> dataArr = fileCfgConditonQC.getDataType();
            BaseLogUtils.info(logger, "getAttachmentFile", "配置规则引擎查询条件...");
            /*配置查询条件*/
            for (String str : dataArr) {
                AttachmentExternalRuleEnginApiReqDTO attachmentExternalRuleEnginApiReqDTO = new AttachmentExternalRuleEnginApiReqDTO();
                /*设置资料类型*/
                attachmentExternalRuleEnginApiReqDTO.setFileType(str);
                /*设置业务CODE*/
                attachmentExternalRuleEnginApiReqDTO.setBusinessCode(fileCfgConditionDTO.getBusinessCode());
                /*设置资方机构CODE*/
                attachmentExternalRuleEnginApiReqDTO.setOrgCode(fileCfgConditionDTO.getOrgCode());
                /*设置资方CODE*/
                attachmentExternalRuleEnginApiReqDTO.setCapitalCode(fileCfgConditionDTO.getCapitalCode());
                /*设置是否有担保人*/
                attachmentExternalRuleEnginApiReqDTO.setAssuranceStatus(fileCfgConditionDTO.getAssuranceStatus());
                /*设置婚姻状态*/
                attachmentExternalRuleEnginApiReqDTO.setMarryStatus(fileCfgConditionDTO.getMarryStatus());
                /*设置是否挂靠*/
                attachmentExternalRuleEnginApiReqDTO.setIsLink(fileCfgConditionDTO.getIsLink());
                /*设置是否厂商*/
                attachmentExternalRuleEnginApiReqDTO.setIsFactory(fileCfgConditionDTO.getIsFactory());
                /*设置是否纸质签署*/
                attachmentExternalRuleEnginApiReqDTO.setIsPaperSign(fileCfgConditionDTO.getIsPaperSign());
                /*设置是否代扣卡*/
                attachmentExternalRuleEnginApiReqDTO.setBankCardType(fileCfgConditionDTO.getBankCardType());
                attachmentExternalRuleEnginApiReqDTO.setCapitalType(fileCfgConditionDTO.getCapitalType());
                /*设置是否团单*/
                attachmentExternalRuleEnginApiReqDTO.setIsGrpBiz(fileCfgConditionDTO.getIsGrpBiz());
                /*设置厂商名称*/
                attachmentExternalRuleEnginApiReqDTO.setSplMfrNm(fileCfgConditionDTO.getSplMfrNm());
                /*设置是否小微企业*/
                attachmentExternalRuleEnginApiReqDTO.setIsSmallBus(fileCfgConditionDTO.getIsSmallBus());
                attList.add(attachmentExternalRuleEnginApiReqDTO);
            }

            /*封装规则引擎需要的查询条件*/
            attachmentConfigQueryApiReqDTO.setAttachmentExternalRuleEnginApiReqDTOs(attList);
            String sysCd = CurrentThreadContext.getFlServiceSysCd();
            String orgCd = CurrentThreadContext.getCurrentOrgCd();
            attachmentConfigQueryApiReqDTO.setBusinessIds(fileCfgConditonQC.getIdsList());
//			attachmentConfigQueryApiReqDTO.setOrgCd(fileCfgConditionDTO.getCstMgrOrgCd());
            attachmentConfigQueryApiReqDTO.setSysCd(sysCd);
            attachmentConfigQueryApiReqDTO.setOrgCd((orgCd == "") ? fileCfgConditionDTO.getCstMgrOrgCd() : orgCd == null ? fileCfgConditionDTO.getCstMgrOrgCd() : orgCd);
            BaseLogUtils.info(logger, "searchFileCfgList", "调用规则引擎获取配置开始...");
            BaseLogUtils.info(logger, "searchFileCfgList", "调用规则引擎请求参数:"+ JSON.toJSONString(attachmentConfigQueryApiReqDTO));

            /*通过规则引擎条件，获取附件配置*/
            DataResultDTO dataREsultDTO = attachmentConfigQueryApiService.getConfigTemplateHasData(attachmentConfigQueryApiReqDTO);
            BaseLogUtils.newLogger("调用规则引擎请求返回结果dataREsultDTO=" + JSON.toJSONString(dataREsultDTO)).info();
            BaseLogUtils.info(logger, "getAttachmentFile", "调用规则引擎获取配置成功...");
            list = (List<AttachmentDataDTO>) dataREsultDTO.getData();
            BaseLogUtils.newLogger("调用规则引擎请求返回结果list=" + JSON.toJSONString(list)).info();
        } catch (Exception e) {
            BaseLogUtils.error(logger, "getAttachmentFile", "获取资料配置失败" + e.toString(), e);
            throw new BaseException("获取资料配置失败，请联系管理员！");
        }
        return list;
    }

    private List<PrjFileInfoVO> getPrjFileInfoVO(List<AttachmentDataDTO> list,String isShowSts) {
        List<PrjFileInfoVO> voList = null;
        BaseLogUtils.info(logger, "getPrjFileInfoVO", "拼装返回数据处理开始...");
        BaseLogUtils.info(logger, "getPrjFileInfoVO", "是否展示所有信息:"+isShowSts);

        if (CollectionUtils.isNotEmpty(list)) {
            Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_MATE_AUD_STS_CD);
            voList = new ArrayList<>();
            PrjFileInfoVO vo;
            //设置路径
            String picServicePath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);
            for (AttachmentDataDTO dataDTO : list) {
                List<AttachmentConfigDataRespDTO> childList = dataDTO.getCfgCdDatas();
                if (CollectionUtils.isNotEmpty(childList)) {
                    for (AttachmentConfigDataRespDTO dataRespDTO : childList) {
                        List<AttachmentConfigDataFileRespDTO> fileRespDTOList = dataRespDTO.getAttachmentConfigDataFileRespDTOS();
                        if (CollectionUtils.isNotEmpty(fileRespDTOList) ) {
                            for (AttachmentConfigDataFileRespDTO fileResp : fileRespDTOList) {
                                vo = new PrjFileInfoVO();
                                if(StringUtils.isNotEmpty(fileResp.getBusinessId())) {
                                    vo.setId(Long.valueOf(fileResp.getBusinessId()));//业务主键
                                }
                                vo.setCfgDtlCd(dataRespDTO.getCfgDtlCd());//配置子编号
                                vo.setDatNm(dataRespDTO.getDatNm());//配置名称
                                vo.setCfgCd(dataDTO.getCfgCd());//配置编号
                                vo.setOrgCd(dataRespDTO.getOrgCd());//配置组织架构代码
                                vo.setCfgNm(dataDTO.getCfgNm());//配置子名称
                                if(StringUtils.isNotEmpty(fileResp.getRecId())) {
                                    vo.setFileId(Long.valueOf(fileResp.getRecId()));//附件ID
                                }
                                //如果有HTTP开头说明是可以访问路径,无需干涉
                                if (StringUtils.isNotBlank(fileResp.getFilePath()) && !fileResp.getFilePath().startsWith("http") && StringUtils.isNotBlank(picServicePath)) {
                                    vo.setFilePath(picServicePath + fileResp.getFilePath());
                                } else {
                                    vo.setFilePath(fileResp.getFilePath());
                                }
                                vo.setFileNm(fileResp.getFileName());//上传名称
                                vo.setCrtTm(fileResp.getFileCrtTm());//上传时间
                                vo.setIsMust(dataRespDTO.getIsMust());//是否必传
                                if (StringUtils.isNotBlank(fileResp.getRecAudStsCd())) {
                                    vo.setAudStsCd(fileResp.getRecAudStsCd());//验证状态
                                } else {
                                    vo.setAudStsCd("0");//验证状态
                                }

                                if (audStsCdMap != null && audStsCdMap.containsKey(vo.getAudStsCd())) {
                                    vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
                                }
                                vo.setMaxNum(dataRespDTO.getMaxNum());
                                vo.setIsAuth(dataRespDTO.getIsAuth());
                                vo.setIsDel(dataRespDTO.getIsDel());
                                vo.setIsValid(dataRespDTO.getIsValid());
                                voList.add(vo);
                            }
                        }else{
                            if(BaseConstant.IS_YESNO_YES_STR.equals(isShowSts)) {
                                vo = new PrjFileInfoVO();
                                vo.setMaxNum(dataRespDTO.getMaxNum());
                                vo.setIsAuth(dataRespDTO.getIsAuth());
                                vo.setIsDel(dataRespDTO.getIsDel());
                                vo.setIsValid(dataRespDTO.getIsValid());
                                vo.setCfgDtlCd(dataRespDTO.getCfgDtlCd());//配置子编号
                                vo.setDatNm(dataRespDTO.getDatNm());//配置名称
                                vo.setCfgCd(dataDTO.getCfgCd());//配置编号
                                vo.setOrgCd(dataRespDTO.getOrgCd());//配置组织架构代码
                                vo.setCfgNm(dataDTO.getCfgNm());//配置子名称
                                //如果有HTTP开头说明是可以访问路径,无需干涉
                                vo.setIsMust(dataRespDTO.getIsMust());//是否必传
                                vo.setAudStsCd("0");//验证状态
                                if (audStsCdMap != null && audStsCdMap.containsKey(vo.getAudStsCd())) {
                                    vo.setAudStsCdNm(audStsCdMap.get(vo.getAudStsCd()));
                                }
                                voList.add(vo);
                            }
                        }
                    }
                }
            }
        }
        return voList;
    }
}
